package com.boomshake.service.impl;

import com.boomshake.common.PageResult;
import com.boomshake.dto.CommissionConfigDTO;
import com.boomshake.entity.CommissionConfig;
import com.boomshake.mapper.CommissionConfigMapper;
import com.boomshake.mapper.StoreMapper;
import com.boomshake.mapper.UserMapper;
import com.boomshake.service.CommissionConfigService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 佣金配置服务实现类
 */
@Service
public class CommissionConfigServiceImpl implements CommissionConfigService {

    @Resource
    private CommissionConfigMapper commissionConfigMapper;
    
    @Resource
    private StoreMapper storeMapper;
    
    @Resource
    private UserMapper userMapper;

    @Override
    public PageResult<CommissionConfigDTO> getCommissionConfigList(Long storeId, int page, int size) {
        // 查询总数
        List<CommissionConfig> configs = commissionConfigMapper.selectList(storeId);
        long total = configs.size();
        
        // 分页处理
        int start = (page - 1) * size;
        int end = Math.min(start + size, configs.size());
        
        if (start >= configs.size()) {
            return PageResult.empty(page, size);
        }
        
        List<CommissionConfig> pageData = configs.subList(start, end);
        
        // 转换为DTO
        List<CommissionConfigDTO> dtoList = pageData.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
        
        return new PageResult<>(dtoList, total, page, size);
    }

    @Override
    public CommissionConfigDTO getCommissionConfigById(Long id) {
        CommissionConfig config = commissionConfigMapper.selectById(id);
        if (config == null) {
            return null;
        }
        return convertToDTO(config);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addCommissionConfig(CommissionConfigDTO configDTO) {
        // 检查是否已存在相同门店和等级的配置
        int count = commissionConfigMapper.countByStoreIdAndLevel(configDTO.getStoreId(), configDTO.getLevel(), null);
        if (count > 0) {
            throw new RuntimeException("该门店已存在相同等级的佣金配置");
        }
        
        // DTO转实体
        CommissionConfig config = new CommissionConfig();
        BeanUtils.copyProperties(configDTO, config);
        
        // 默认启用
        if (config.getIsActive() == null) {
            config.setIsActive(1);
        }
        
        // 插入数据
        commissionConfigMapper.insert(config);
        
        return config.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCommissionConfig(CommissionConfigDTO configDTO) {
        // 检查记录是否存在
        CommissionConfig existConfig = commissionConfigMapper.selectById(configDTO.getId());
        if (existConfig == null) {
            return false;
        }
        
        // 如果修改了门店或等级，需要检查是否与其他配置冲突
        if ((configDTO.getStoreId() != null && !configDTO.getStoreId().equals(existConfig.getStoreId())) 
                || (configDTO.getLevel() != null && !configDTO.getLevel().equals(existConfig.getLevel()))) {
            int count = commissionConfigMapper.countByStoreIdAndLevel(
                    configDTO.getStoreId() != null ? configDTO.getStoreId() : existConfig.getStoreId(),
                    configDTO.getLevel() != null ? configDTO.getLevel() : existConfig.getLevel(),
                    configDTO.getId());
            if (count > 0) {
                throw new RuntimeException("该门店已存在相同等级的佣金配置");
            }
        }
        
        // DTO转实体
        CommissionConfig config = new CommissionConfig();
        BeanUtils.copyProperties(configDTO, config);
        
        // 更新数据
        return commissionConfigMapper.update(config) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteCommissionConfig(Long id) {
        // 检查记录是否存在
        CommissionConfig config = commissionConfigMapper.selectById(id);
        if (config == null) {
            return false;
        }
        
        // 删除数据
        return commissionConfigMapper.deleteById(id) > 0;
    }

    @Override
    public List<CommissionConfigDTO> getStoreCommissionRates(Long storeId) {
        // 获取门店所有佣金配置
        List<CommissionConfig> configs = commissionConfigMapper.selectList(storeId);
        
        // 转换为DTO
        return configs.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchUpdateStoreCommissionRates(Long storeId, List<CommissionConfigDTO> configDTOs) {
        // 参数校验
        if (storeId == null || configDTOs == null || configDTOs.isEmpty()) {
            return false;
        }
        
        try {
            // 获取当前门店的所有配置
            List<CommissionConfig> existConfigs = commissionConfigMapper.selectList(storeId);
            
            for (CommissionConfigDTO configDTO : configDTOs) {
                // 设置门店ID
                configDTO.setStoreId(storeId);
                
                // 查找是否已存在该等级的配置
                boolean exists = false;
                for (CommissionConfig existConfig : existConfigs) {
                    if (existConfig.getLevel().equals(configDTO.getLevel())) {
                        // 更新已存在的配置
                        configDTO.setId(existConfig.getId());
                        updateCommissionConfig(configDTO);
                        exists = true;
                        break;
                    }
                }
                
                // 不存在则新增
                if (!exists) {
                    addCommissionConfig(configDTO);
                }
            }
            
            return true;
        } catch (Exception e) {
            throw new RuntimeException("批量更新佣金配置失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 实体转DTO，并填充关联信息
     * @param config 实体
     * @return DTO
     */
    private CommissionConfigDTO convertToDTO(CommissionConfig config) {
        if (config == null) {
            return null;
        }
        
        CommissionConfigDTO dto = new CommissionConfigDTO();
        BeanUtils.copyProperties(config, dto);
        
        // 填充门店名称
        if (config.getStoreId() != null && config.getStoreId() > 0) {
            dto.setStoreName(storeMapper.getStoreNameById(config.getStoreId()));
        } else if (config.getStoreId() != null && config.getStoreId() == 0) {
            dto.setStoreName("全局配置");
        }
        
        // 填充创建人姓名
        if (config.getCreatedBy() != null) {
            dto.setCreatorName(userMapper.getUsernameById(config.getCreatedBy()));
        }
        
        return dto;
    }
} 